﻿using HslCommunication.MQTT;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DataCapture.Helper.PublicHelp;

namespace DataCapture.Helper
{
    class MQTTConsoleServer
    {
        private MqttServer mqttServer;

        public MqttServer MqttServer => mqttServer;

        //通过 Lazy<T>，实现了一个线程安全的单例模式。因为 Lazy<T> 的 Value 属性是线程安全的。
        private static readonly Lazy<MQTTConsoleServer> instance = new Lazy<MQTTConsoleServer>(() => new MQTTConsoleServer());
        public static MQTTConsoleServer Instance => instance.Value;

        public MQTTConsoleServer()
        {
            mqttServer = new MqttServer();
            mqttServer.OnClientApplicationMessageReceive += MqttClient_OnMqttMessageReceived;
            mqttServer.ServerStart(1883);
            mqttServer.ClientVerification += MqttServer_ClientVerification;//增加身份验证

            if (MainForm.Instance != null)
            {
                Log4NetHelper.Debug("MQTT服务器启动成功，端口号：1883");
            }
        }

        private int MqttServer_ClientVerification(MqttSession mqttSession, string clientId, string userName, string passwrod)
        {
            if (userName == "admin" && passwrod == "123456") return 0;
            return 4;
            // 返回错误码说明(后续可扩展):1: 不可接受的版本协议  2: 拒绝标识符  3: 服务器不可用  4: 错误的用户名和密码 5: 未被授权
        }

        /// <summary>
        /// MQTT消息发送：服务端向客户端发送消息
        /// </summary>
        /// <param name="deviceData">数据源</param>
        /// <param name="topic">主题</param>
        public void ForwardData<T>(T deviceData, string topic)
        {
            try
            {
                // 参数校验
                if (string.IsNullOrWhiteSpace(topic))
                {
                    Log4NetHelper.Debug("Topic订阅为空");
                    return;
                }

                if (mqttServer == null || !mqttServer.IsStarted)
                {
                    return;
                }

                if (deviceData == null)
                {
                    return;
                }

                // 构建 JSON 数据
                var json = JObject.FromObject(deviceData);
                var payload = Encoding.UTF8.GetBytes(json.ToString());

                mqttServer.PublishTopicPayload(topic, payload);
            }
            catch (Exception ex) when (ex is SystemException || ex is JsonException)
            {
                // 记录日志（建议替换为实际的日志框架）
                Log4NetHelper.Debug($"MQTT消息发送失败: {ex}");

                // 安全地更新 UI
                if (MainForm.Instance != null && !MainForm.Instance.IsDisposed)
                {
                    Log4NetHelper.Debug("MQTT消息发送失败，请查看日志获取更多信息");
                }
            }
        }

        /// <summary>
        /// 当收到MQTT客户端的消息时触发
        /// </summary>
        /// <param name="session"></param>
        /// <param name="message"></param>
        private void MqttClient_OnMqttMessageReceived(MqttSession session, MqttClientApplicationMessage message)
        {
            if (message.Topic == "TakeInfoDataRequest") //任务台账信息数据请求
            {
                // MainForm.Instance.ReadTaskInfoData();
                DataProcessor.ReadTaskInfoData();
            }
        }
        /// <summary>
        /// 关闭MQTT
        /// </summary>
        public void CloseMqtt()
        {
            if (mqttServer != null)
            {
                mqttServer.DeleteRetainTopic("TakeInfoDataRequest");
                mqttServer.ServerClose();
                mqttServer.Dispose();
            }
        }
    }
}
